package edu.bw.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

@Component
public class TransactionManager {
    @Autowired
    private ConnectionFactory connectionFactory;
    @Autowired
    private ThreadLocal<Connection> threadLocal;
    public void beginTransaction() {
        try {
            connectionFactory.getConnection().setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public void commit() {
        try {
            connectionFactory.getConnection().commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public void rollback() {
        try {
            connectionFactory.getConnection().rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public void close() {
        try {
            connectionFactory.getConnection().close();
            threadLocal.remove();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
